//
//  ViolationSubmitController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/5/5.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class ViolationSubmitController: BaseController{
    var submitTable:UITableView!//数据表格
    var orderID = ""//订单编号
    var totalAmount = ""//总费用
    var totalScore = ""//总扣分
    var vioInfoArray = Array<VioInfoModel>()
    //订单编号
    lazy var headerView: OrderSubmitHeader = {
        let view = OrderSubmitHeader(frame: CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: 65))
        return view
    }()
    lazy var bottomView: OrderSubmitBottom = {
        let view = OrderSubmitBottom(frame: CGRect(x: 0, y: kScreenH - 69, width: kScreenW, height: 69))
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupNavBar(title: "订单详情", isback: true, appearWay: 3, isright: false)//自定义导航
        self.headerView.orderID = orderID
    }
    override func viewWillAppear(_ animated: Bool) {
        if reachability.isReachable {
            loadVioInfiList()
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
        //初始化表格
        submitTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH + 65,width:kScreenW,height:kScreenH - kStatusBarH - kNavigationBarH - 134),style: UITableViewStyle.plain)
        submitTable?.delegate = self
        submitTable?.dataSource = self
        submitTable?.backgroundColor = tableBgColor
        submitTable?.separatorStyle = UITableViewCellSeparatorStyle.none
        submitTable?.rowHeight = 210
        self.view.addSubview(submitTable!)
        self.view.addSubview(self.headerView)
    }
}
extension ViolationSubmitController{
    func loadVioInfiList(){
        let urlString = "\(projectUrl)/order/car/detail/\(orderID)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,subJson) : (String,JSON) in json["rdata"]["list"] {
                        let model = VioInfoModel.init(dic: subJson)
                        self.vioInfoArray.append(model)
                    }
                    if self.vioInfoArray.count > 0 { //如果存在
                        self.submitTable.reloadData()
                    }
                    self.totalAmount = json["rdata"]["totalAmount"].rawString()!
                    self.totalScore = json["rdata"]["totalScore"].rawString()!
                    self.bottomView.totalAmountLabel.text = self.totalAmount
                    self.bottomView.totalScoreLabel.text = "\(self.totalScore)分"
                    self.bottomView.ostatus = Int(json["rdata"]["ostatus"].rawString()!)
                    self.view.addSubview(self.bottomView)
                }
                else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    //选择支付方式
    func toChoicePay(sender:UIButton){
        let pc = PayController()
        pc.orderID = self.orderID
        pc.totalAmount = self.totalAmount
        pc.modelType = "illeagal"
        self.present(pc, animated: true, completion: nil)
    }
    func alertFun(sender:UIButton){
        if 0 == sender.tag {
           toChoicePay(sender:sender)
        }else{
            var urlString = ""
            if 1 == sender.tag {//抢单
                urlString = "\(projectUrl)/order/car/accept/\(orderID)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            }
            if 2 == sender.tag {//完成订单
                urlString = "\(projectUrl)/order/car/finish/\(orderID)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            }
            toOperatOrder(url: urlString)
        }
    }
}
extension ViolationSubmitController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vioInfoArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell: OrderSubmitCell? = tableView.dequeueReusableCell(withIdentifier: "submitCell") as? OrderSubmitCell
        if cell == nil {
            cell = OrderSubmitCell(style: UITableViewCellStyle.default,reuseIdentifier: "submitCell")
        }
        if vioInfoArray.count > 0 {
            let model = vioInfoArray[(indexPath as NSIndexPath).row]
            cell?.configCellDateWithModel(model: model,total:vioInfoArray.count,num:(indexPath as NSIndexPath).row + 1)
        }
        return cell!
    }
}
